import { getToken } from '@/utils/auth'
import Home from '@/views/home'


const loadView = (viewPath) => {
    // 用字符串模板实现动态 import 从而实现路由懒加载，@/views/ 是必须的
    return () => import(`@/views/${viewPath}`)
}

const filterAsyncRouter = (routeList) => {
    return routeList.map((route) => {
        route.meta = route.meta || {name:''}
        route.meta.name = route.meta.name || ''
        if (route.component) {
            if (route.component === 'Home') {
                // 如果 component = Home 说明是布局组件
                // 将真正的布局组件赋值给它
                route.component = Home
            } else {
                // 如果不是布局组件就只能是页面的引用了
                // 利用懒加载函数将实际页面赋值给它
                route.component = loadView(route.component)
                if(route.meta && route.meta.keepAlive){
                    state.keepAliveViews.push(route.component)
                }
            }
            // 判断是否存在子路由，并递归调用自己
            if (route.children && route.children.length) {
                route.children = filterAsyncRouter(route.children)
            }
        }
        return route
    })
}

const apposeAsyncRouter = (routeList,res)=>{
    if(!res) res = []
    routeList.forEach(r=>{
        res.push(r)
        if(r.children && r.children.length)
        apposeAsyncRouter(r.children,res)
    });
    return res
}

const state = {
    routes: [],
    registered:false,
    keepAliveViews:[]
}
const mutations = {
    registration:(state)=>{
        state.registered = true
    }
}
const actions = {
    getAccessRoutes:async({ commit })=>{
        var { data } = await $y.api.system.route.getAccessRoutes(getToken())
        $y.cache.set('route',apposeAsyncRouter(data))
        var accessRoutes = filterAsyncRouter(data)
        commit('registration')
        return accessRoutes;
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}